using HarmonyLib;
using System.Reflection;
using UnityEngine;
using Duckov.Modding; // 引入官方ModBehaviour所在命名空间
using Duckov.Quests.Tasks;
using System;

// 保持唯一命名空间
namespace KangyuPL_IngoreQuestCondMod
{
    // 继承官方要求的ModBehaviour
    public class ModBehaviour : Duckov.Modding.ModBehaviour
    {
        // 1. 定义唯一的Mod ID（用于Harmony和官方标识）
        private const string ModId = "com.kangyupl.ignorequestcond";

        // 2. 反射字段缓存（核心逻辑依赖）
        private static FieldInfo? withWeaponField;
        private static FieldInfo? requireHeadShotField;
        private static FieldInfo? withoutHeadShotField;
        private static FieldInfo? requireBuffField;
        private static FieldInfo? requireSceneIDField;
        // 3. Harmony实例（用于补丁管理）
        private Harmony? harmony;

        // 4. 临时存储原始值（主线程安全）
        private static bool _originalWithWeapon;
        private static bool _originalRequireHeadShot;
        private static bool _originalWithoutHeadShot;
        private static bool _originalRequireBuff;
        private static string? _originalRequireSceneID;


        // 官方要求：OnEnable - Mod激活时调用（初始化逻辑）
        private void OnEnable()
        {
            Debug.Log($"[{ModId}] 已激活");

            // 初始化所有需要修改的反射字段（新增场景、爆头、Buff字段）
            withWeaponField = AccessTools.Field(typeof(QuestTask_KillCount), "withWeapon");
            requireHeadShotField = AccessTools.Field(typeof(QuestTask_KillCount), "requireHeadShot");
            withoutHeadShotField = AccessTools.Field(typeof(QuestTask_KillCount), "withoutHeadShot");
            requireBuffField = AccessTools.Field(typeof(QuestTask_KillCount), "requireBuff");
            requireSceneIDField = AccessTools.Field(typeof(QuestTask_KillCount), "requireSceneID");

            // 校验所有字段是否存在（缺一则Mod失效）
            if (withWeaponField == null || requireHeadShotField == null || withoutHeadShotField == null || requireBuffField == null || requireSceneIDField == null)
            {
                Debug.LogError($"[{ModId}] 初始化失败：缺少关键字段（可能游戏版本更新）");
                return;
            }

            // 初始化Harmony并注册补丁（此处逻辑不变，仅字段校验部分修改）
            harmony = new Harmony(ModId);
            try
            {
                var targetMethod = AccessTools.Method(typeof(QuestTask_KillCount), "Health_OnDead");
                harmony.Patch(
                    targetMethod,
                    prefix: new HarmonyMethod(typeof(ModBehaviour), nameof(HealthOnDeadPrefix)),
                    postfix: new HarmonyMethod(typeof(ModBehaviour), nameof(HealthOnDeadPostfix))
                );
                Debug.Log($"[{ModId}] 补丁注册成功");
            }
            catch (Exception e)
            {
                Debug.LogError($"[{ModId}] 补丁注册失败：{e.Message}");
            }
        }


        // 官方要求：OnDisable - Mod禁用时调用（清理逻辑）
        private void OnDisable()
        {
            Debug.Log($"[{ModId}] 已禁用");

            // 清理Harmony补丁（逻辑不变）
            if (harmony != null)
            {
                harmony.UnpatchAll(ModId);
                Debug.Log($"[{ModId}] 补丁已清理");
            }

            // 重置所有反射字段（新增其他字段的重置）
            withWeaponField = null;
            requireHeadShotField = null;
            withoutHeadShotField = null;
            requireBuffField = null;
            requireSceneIDField = null;
        }


        // 5. 核心补丁逻辑（Prefix：临时禁用withWeapon）
        private static void HealthOnDeadPrefix(QuestTask_KillCount __instance)
        {
            // 校验字段非空（避免空引用）
            if (withWeaponField == null || requireHeadShotField == null || withoutHeadShotField == null || requireBuffField == null || requireSceneIDField == null)
                return;

            // 1. 暂存所有字段的原始值
            _originalWithWeapon = (bool)withWeaponField.GetValue(__instance);
            _originalRequireHeadShot = (bool)requireHeadShotField.GetValue(__instance);
            _originalWithoutHeadShot = (bool)withoutHeadShotField.GetValue(__instance);
            _originalRequireBuff = (bool)requireBuffField.GetValue(__instance);
            _originalRequireSceneID = (string?)requireSceneIDField.GetValue(__instance);

            // 2. 临时修改字段，让所有条件失效
            withWeaponField.SetValue(__instance, false);          // 跳过武器限制
            requireHeadShotField.SetValue(__instance, false);     // 跳过“必须爆头”限制
            withoutHeadShotField.SetValue(__instance, false);     // 跳过“禁止爆头”限制
            requireBuffField.SetValue(__instance, false);         // 跳过Buff限制
            requireSceneIDField.SetValue(__instance, string.Empty);// 跳过场景限制（空字符串表示不限制场景）
        }

        // 6. 核心补丁逻辑（Postfix：恢复原始值）
        private static void HealthOnDeadPostfix(QuestTask_KillCount __instance)
        {
            // 校验字段非空（避免空引用）
            if (withWeaponField == null || requireHeadShotField == null || withoutHeadShotField == null || requireBuffField == null || requireSceneIDField == null)
                return;

            // 恢复所有字段的原始值（与Prefix修改顺序对应）
            withWeaponField.SetValue(__instance, _originalWithWeapon);
            requireHeadShotField.SetValue(__instance, _originalRequireHeadShot);
            withoutHeadShotField.SetValue(__instance, _originalWithoutHeadShot);
            requireBuffField.SetValue(__instance, _originalRequireBuff);
            requireSceneIDField.SetValue(__instance, _originalRequireSceneID);
        }
    }
}
